package com.kili.cloud.shorturl.service.impl;

import com.kili.cloud.common.exception.ExceptionUtils;
import com.kili.cloud.common.util.BeanUtils;
import com.kili.cloud.shorturl.repository.entity.Customer;
import com.kili.cloud.shorturl.enumerate.IsDeletedEnum;
import com.kili.cloud.shorturl.service.model.CustomerModel;
import com.kili.cloud.shorturl.repository.CustomerDao;
import com.kili.cloud.shorturl.service.CustomerService;
import com.kili.common.Exception.ExceptionType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 客户信息服务实现类
 * @author: tom.liu
 * @date: 2019/6/14 16:47
 */
@Service
public class CustomerServiceImpl implements CustomerService {
    private static Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);

    @Autowired
    CustomerDao customerDao;

    @Override
    public List<CustomerModel> selectBySelective(CustomerModel customerModel) {
        Customer customer = new Customer();
        BeanUtils.copyProperties(customerModel, customer);
        List<Customer> list = customerDao.selectBySelective(customer);
        ArrayList modelList = new ArrayList<CustomerModel>();
        BeanUtils.copyProperties(list, modelList, Customer.class, CustomerModel.class);
        return modelList;
    }

    @Override
    public  long validateUser(String userName, String password) {
        logger.debug("验证用户信息：userName={},password={}", userName, password );
        if(StringUtils.isBlank(userName) ){
            logger.info("用户名为空");
            throw ExceptionUtils.getBussinessException(ExceptionType.BIZ_VERIFY_ERROR, "500", "user name is null" );
        }
        if(StringUtils.isBlank(password)){
            logger.info("密码为空");
            throw ExceptionUtils.getBussinessException(ExceptionType.BIZ_VERIFY_ERROR, "500", "password is null" );
        }

        CustomerModel customerModel = new CustomerModel();
        customerModel.setCustomerName(userName);
        customerModel.setPassword(password);
        customerModel.setIsDeleted(IsDeletedEnum.NO.getCode());
        List<CustomerModel> list = selectBySelective(customerModel);

        if(CollectionUtils.isEmpty(list)){
            logger.info("用户信息不存在");
            throw ExceptionUtils.getBussinessException(ExceptionType.BIZ_VERIFY_ERROR, "500", "user information does not exis" );
        }

        if(list.size() > 1){
            logger.info("用户信息异常：重复的用户信息");
            throw ExceptionUtils.getBussinessException(ExceptionType.BIZ_VERIFY_ERROR, "500", "abnormal user information：repeat" );
        }
        logger.debug("验证用户信息：通过");
        return list.get(0).getId();
    }
}
